package com.tzbank.mpass;

import com.alibaba.fastjson.JSON;
import com.tzbank.mpass.enums.DeliveryType;
import com.tzbank.mpass.model.*;
import com.tzbank.mpass.util.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author youkun
 * @data 2.18/7/6
 * mpass消息推送方法
 *
 */
public class MpassPushUtils {

    /**
     * 推送接口服务地址
     */
    private static String mpsAPIAddress = "https://cn-hangzhou-mps-api.cloud.alipay.com";

    /**
     * 应用标识
     */
    private static final String appId       = "868A024261811";

    /**
     * 环境标识
     */
    private static final String workSpaceId   = "default";

    /**
     * 字符集设置
     */
    private static final String charSet     = "UTF-8";

    /**
     * RSA私钥，要求2048位的密钥对，接口调用前请现在mpaas控制台登记该RSA私钥对应的公钥
     */
    private static final String rsaKey ="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDDqcg3y1grbI65" +
            "yF2xTqw0UjC+Yc6MXpDw79DY3CbYMSohhF4pA2YYD0+gZ6RiY1V0M/3JmHT/TW1T" +
            "e4eodThEYz1kaOprMMYDC3axdsSCGQDs32MTmQDeybLYGHN3iMi/yRKSWGivATN0" +
            "HFWvPQpaX6jURlUNMsb/7820BMPrxqFTF8iURNYrwC65/1P/FPtJIzAvp1JqeAYV" +
            "DP0GUOmoRzUyhRlPEmXl9/oW6/w/L01cHLhxszlwYQ/oT4INXgNbZGTA8teu3+6w" +
            "oK+qmuaN9Hjy5QLVW0CtHKzdR54oG850WSZmqk6148SrFZDzw/Us2Q+YXT+WSErb" +
            "1hHUZc5TAgMBAAECggEBALTUwDdYlncjkFEBbh4FYL/GSkhZqoQujfQvH6yc4sWh" +
            "wpdRd5ieDIgl9miAAPvxZDPOLTpYzaB6VZT3MOwu0b7anQ2krSo93HNJ7/uZkYnP" +
            "Q/ynhDDDkntUnBZ9mpGZ+DbPxXs9fBppmL0xxrr7Rgs6J5VwHwDgsewuG8XJNa07" +
            "u1k4RhQ90gGIe5hwSGO3XgwyAoSaAQnq5sLOnvjezdIyA0vUrvT9/MMXYlbqptbV" +
            "wm5S+MPz+vdbCONuNvV4HmZ3bveorZ6QP3VL+t6G/NMNnQGM7H/7vdcvazrRI0gb" +
            "fE3erxY0vlwLfW/28UGlV7JhG76ZZoF1GcCNst/7U5kCgYEA5ie+CrCPbXExme/K" +
            "THjIHHXVFqQ1QbVXReNbQxAB5iwXCR21TFL7V+axiel1kWM/JldWgb+W5+rtePbN" +
            "mNB1Tdl8l8Q/b7X69P35MSl+XCGxS2rbGXo5A3s9ToZPSrUU46QXUgh/I6WVFBhK" +
            "CaUZjZ421ZEWTm3TFDYg/aTSw8UCgYEA2aJ/47/B+liD2XA6V8qrqCO1B/A7Ac8k" +
            "j23UFugpyG5n7nMsrknVhtj6OhFNBfXFzh3G7GA0Z/V0vPwjCzMqmh3gJyta98j1" +
            "As3Jfw9jK3BOLwKQP8TW8F9qx9jSY0KLe3muCexhmIU8ietci8OLimGUQd2hyJeF" +
            "gHhkaI//szcCgYAp4Ak/wKgX7YRs0agpCcC/DOFcYTwfXHMokBlGtl7iFhuK2RDn" +
            "diGs+JhM02FEtp4Cx9lBei5mu+PBIoZ9y0/MfkmhA1/XX3DtqlfwjfAjqy2q3yJG" +
            "HGrLK10YMG+01AWc9XoYvtsDDVl2coTmBFgF4EdxzBgW5PyGrOKLw7VlUQKBgFkR" +
            "/pFxe6w/6cZl/hrMIbDw3Dhhg2TcKDRjWLf/UIptVS/sB09VfIRx7Qcy6XkU+12+" +
            "Jhm7zfb2KE7oSlddG4Rz0bd2MQbUQiJhoqPT4lx23Ci1PeA7aVR7WLJt9L0XEQr5" +
            "49a/3bmUXhB8OSYiY8vA3/KNCJeWG9dWbpG0zYvFAoGAQj5h4xUeY1hS87f9REiQ" +
            "O59F5IO5UZ7oCAq22gZz+OFgOcBOlodW6GNnrof5IoYil/wHnGhJ+Wt6kSa0V+70" +
            "h+mAsocwEuCz4y+mdSUxuyseUUmrgOViyG5Nu44qUgW583x06AqwBazeMxbSAAy8" +
            "uOqctdDzpnJFtzqOoPfOymk=";

    /**
     *
     * @param pushBroadcastReq
     * @return
     * @throws Exception
     * 群发推送
     */
    public static HttpClientUtil.HttpInvokeResult pushBroadcast(PushBroadcastReq pushBroadcastReq ) throws Exception{
        if(pushBroadcastReq==null){
            throw new Exception("pushBroadcastReq is null");
        }
        String reqContent = JSON.toJSONString(pushBroadcastReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);
        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/push/pushbroadcast/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //此处的成功是指推送任务接受成功，由于消息推送是异步过程，所以具体有没有下发成功需要根据客户端实际情况进行判断
        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     * 批量推送
     * @param pushMultipleReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult pushMultiple(PushMultipleReq pushMultipleReq ) throws Exception{
        if(pushMultipleReq==null){
            throw new Exception("pushMultipleReq is null");
        }
        String reqContent = JSON.toJSONString(pushMultipleReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);
        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/push/pushmultiple/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //此处的成功是指推送任务接受成功，由于消息推送是异步过程，所以具体有没有下发成功需要根据客户端实际情况进行判断
        //接口调用结果码参考PushResultEnum枚举类
        return  HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     * 简单推送
     * @param pushSimpleReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult pushSimple(PushSimpleReq pushSimpleReq ) throws Exception{
        if(pushSimpleReq==null){
            throw new Exception("pushSimpleReq is null");
        }

        String reqContent = JSON.toJSONString(pushSimpleReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/push/pushsimple/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //此处的成功是指推送任务接受成功，由于消息推送是异步过程，所以具体有没有下发成功需要根据客户端实际情况进行判断
        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     *  模板推送
     * @param pushTemplateReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult pushTemplate(PushTemplateReq pushTemplateReq ) throws Exception{
        if(pushTemplateReq==null){
            throw new Exception("pushTemplateReq is null");
        }
        String reqContent = JSON.toJSONString(pushTemplateReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/push/pushtemplate/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //此处的成功是指推送任务接受成功，由于消息推送是异步过程，所以具体有没有下发成功需要根据客户端实际情况进行判断
        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     * 手机绑定
     * @param bindAppReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult  bindApp(BindAppReq bindAppReq) throws Exception{
        if(bindAppReq==null){
            throw new Exception("bindAppReq is null");
        }
        String reqContent = JSON.toJSONString(bindAppReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/bind/bind/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }

    /**
     * 手机解绑
     * @param unbindAppReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult  unbindApp(UnbindAppReq unbindAppReq) throws Exception{
        if(unbindAppReq==null){
            throw new Exception("unbindAppReq is null");
        }
        String reqContent = JSON.toJSONString(unbindAppReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/bind/unbind/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }


    /**
     * 设备上报 ios 推送需要上报
     * @param reportAppReq
     * @return
     * @throws Exception
     */
    public static  HttpClientUtil.HttpInvokeResult  reportApp(ReportAppReq reportAppReq) throws Exception{
        if(reportAppReq==null){
            throw new Exception("reportAppReq is null");
        }
        String reqContent = JSON.toJSONString(reportAppReq);

        String sign = SignUtil.sign(reqContent,rsaKey,charSet);

        //sign字段放在path里面，所以需要预先做敏感字符替换
        sign = sign.replace('/', '_').replace('+', '-');
        String url = String.format("%s/deviceinfo/report/%s/%s/%s", mpsAPIAddress, appId,workSpaceId, sign);

        //接口调用结果码参考PushResultEnum枚举类
        return HttpClientUtil.invokePost(url, reqContent);
    }


    public static void main(){

        //群发推送
        PushBroadcastReq pushBroadcastReq = new PushBroadcastReq();
        pushBroadcastReq.setTaskName("测试任务");
        //群发只有两种模式，针对安卓设备或者针对IOS设备
        pushBroadcastReq.setDeliveryType(DeliveryType.DEVICE_ANDROID.getValue());
        pushBroadcastReq.setExpiredSeconds(600);

        //请根据实际的模版名称进行设置
        pushBroadcastReq.setTemplateName("template");

        //模版中配置的变量值，请根据实际模版中的变量进行设置
        Map<String,String> templateKV = new HashMap<String, String>();
        templateKV.put("title", "title-");
        templateKV.put("content", "content-");
        pushBroadcastReq.setTemplatekv(templateKV);

        Map<String,String> extendedParam = new HashMap<String, String>();
        extendedParam.put("test","自定义扩展参数");
        pushBroadcastReq.setExtended_params(extendedParam);

        pushBroadcastReq.setMsgkey(String.valueOf(System.currentTimeMillis()));
        try {
            MpassPushUtils.pushBroadcast(pushBroadcastReq);
        } catch (Exception e) {
            e.printStackTrace();
        }



        //批量推送
        PushMultipleReq pushMultipleReq = new PushMultipleReq();
        pushMultipleReq.setTaskName("测试任务");
        pushMultipleReq.setDeliveryType(DeliveryType.DEVICE_ANDROID.getValue());
        pushMultipleReq.setExpiredSeconds(600);

        //请根据实际的模版名称进行设置
        pushMultipleReq.setTemplateName("template");

        Map<String,TargetMsgInfo> targetMsgInfoMap = new HashMap<String, TargetMsgInfo>(2);

        TargetMsgInfo targetMsgInfo1 = new TargetMsgInfo();
        //模版中配置的变量值，请根据实际模版中的变量进行设置
        Map<String,String> templateKVv = new HashMap<String, String>();
        templateKVv.put("title", "title-");
        templateKVv.put("content", "content-");
        targetMsgInfo1.setTemplatekv(templateKVv);
        targetMsgInfo1.setMsgkey(String.valueOf(System.currentTimeMillis()));
        //请根据实际的设备标识或者用户标识进行替换
        targetMsgInfoMap.put("1fe792f00163100080a730300a19467a",targetMsgInfo1);

        TargetMsgInfo targetMsgInfo2 = new TargetMsgInfo();
        //模版中配置的变量值，请根据实际模版中的变量进行设置
        Map<String,String> templateKV2 = new HashMap<String, String>();
        templateKV2.put("title", "title-2");
        templateKV2.put("content", "content-2");
        targetMsgInfo2.setTemplatekv(templateKV2);
        targetMsgInfo2.setMsgkey(String.valueOf(System.currentTimeMillis())+"121");
        //请根据实际的设备标识或者用户标识进行替换
        targetMsgInfoMap.put("1fe792f00163100080a730300a19467b",targetMsgInfo2);
        pushMultipleReq.setTarget_msginfo(targetMsgInfoMap);


        Map<String,String> extendedParams = new HashMap<String, String>();
        extendedParams.put("test","自定义扩展参数");
        pushMultipleReq.setExtended_params(extendedParams);
        try {
            MpassPushUtils.pushMultiple(pushMultipleReq);
        } catch (Exception e) {
            e.printStackTrace();
        }


        //简单推送
        PushSimpleReq pushSimpleReq = new PushSimpleReq();
        pushSimpleReq.setTaskName("测试任务");
        pushSimpleReq.setContent("简单推送样例-内容");
        pushSimpleReq.setTitle("简单推送样例-标题");
        pushSimpleReq.setUri("http://127.0.0.1");
        pushSimpleReq.setDeliveryType(DeliveryType.DEVICE_ANDROID.getValue());
        pushSimpleReq.setExpiredSeconds(600);

        Map<String,String> extendedParamss = new HashMap<String, String>();
        extendedParamss.put("test","自定义扩展参数");
        pushSimpleReq.setExtended_params(extendedParamss);

        Map<String,String> target = new HashMap<String, String>();
        String msgKey = String.valueOf(System.currentTimeMillis());
        target.put("test",msgKey);
        pushSimpleReq.setTarget_msgkey(target);
        try {
            MpassPushUtils.pushSimple(pushSimpleReq);
        } catch (Exception e) {
            e.printStackTrace();
        }



        //模板推送
        PushTemplateReq pushTemplateReq = new PushTemplateReq();
        pushTemplateReq.setTaskName("测试任务");
        pushTemplateReq.setDeliveryType(DeliveryType.DEVICE_ANDROID.getValue());
        pushTemplateReq.setExpiredSeconds(600);

        //请根据实际的模版名称进行设置
        pushTemplateReq.setTemplateName("template");

        //模版中配置的变量值，请根据实际模版中的变量进行设置
        Map<String,String> templateKVw = new HashMap<String, String>();
        templateKVw.put("title", "title-");
        templateKVw.put("content", "content-");
        pushTemplateReq.setTemplatekv(templateKVw);

        Map<String,String> extendedParamsss = new HashMap<String, String>();
        extendedParamsss.put("test","自定义扩展参数");
        pushTemplateReq.setExtended_params(extendedParamsss);

        Map<String,String> targetsss = new HashMap<String, String>();
        String msgKeyss = String.valueOf(System.currentTimeMillis());
        targetsss.put("1fe792f00163100080a730300a19467a",msgKeyss);
        pushTemplateReq.setTarget_msgkey(targetsss);
        try {
            MpassPushUtils.pushTemplate(pushTemplateReq);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
